<?php
// +----------------------------------------------------------------------
// | huicmf [ huicmf快速开发框架 ]
// +----------------------------------------------------------------------
// | Copyright (c) 2022~2024 https://xiaohuihui.cc All rights reserved.
// +----------------------------------------------------------------------
// | Author: 小灰灰 <762229008@qq.com>
// +----------------------------------------------------------------------
// | Info: 方便排查哪个请求可能有内存泄露
// +----------------------------------------------------------------------

namespace app\middleware;

use Webman\App;
use Webman\MiddlewareInterface;
use Webman\Http\Response;
use Webman\Http\Request;

class MemoryDetect implements MiddlewareInterface
{

    public function process(Request $request, callable $handler): Response
    {
        $response = $handler($request);
        $worker   = App::worker();
        if ( ! $worker || $worker->id !== 0) {
            return $response;
        }
        static $memory = 0;
        $uri    = $request->uri();
        $method = $request->method();
        if ($memory === 0) {
            $memory = memory_get_usage(true);
        }
        $usage  = memory_get_usage(true);
        $diff   = $usage - $memory;
        $memory = $usage;
        if ($diff) {
            file_put_contents(runtime_path('logs/memory-'.date('Y-m-d').'.log'),
                date('Y-m-d H:i:s')." $memory $diff $method $uri \n", FILE_APPEND);
        }

        return $response;
    }

}
